const float gravity = 9.81;

float getVelocity(float dt, float value, AccData * data) {
  dt = dt / 1000;
  data->acceleration[2] = value * gravity;

  // Set dead zone.
  if (value <= 0.1 && value >= -0.1) {
    data->acceleration[2] = 0;  
  }
  
  if (data->acceleration[2] > data->acceleration[1] && data->positive == -1) {
    // Don't force direction because we are using tilt mechanic.
    data->positive = 1;
  } 
  else if (data->acceleration[2] < data->acceleration[1] && data->positive == -1) {
    // Don't force direction because we are using tilt mechanic.
    data->positive = 0;
  }  
  data->positive = -1;

  if (data->positive == 1 && data->acceleration[2] != 0) {
    data->acceleration[2] = data->acceleration[2];
  } 
  else if (data->positive == 0  && data->acceleration[2] != 0) {
    data->acceleration[2] = data->acceleration[2];
  }

  data->velocity[1] = data->velocity[0] + (data->acceleration[0] +
    4 * data->acceleration[1] + data->acceleration[2]) * dt * 2 / 6;

  if (data->positive == 1 && data->velocity[1] < 0 ||
    data->positive == 0 && data->velocity[1] > 0) {
    data->velocity[1] = 0;
  }

  data->acceleration[0] = data->acceleration[1];
  data->acceleration[1] = data->acceleration[2];  
  data->velocity[0] = data->velocity[1];
  data->position[0] = data->position[1];

  if (data->acceleration[2] == 0) {
    ++data->count;
  } 
  else {
    data->count = 0;
  }

  if (data->count >= 15 ) {
    data->positive = -1;
    data->velocity[1] = 0;
    data->velocity[0] = 0;
  }

  return data->velocity[0];
}

